package basics.algorithm.sort;

/**
 * 插入排序
 * 
 * @author lisy
 */
public class InsertionSort {
	
	public static void insertionSort1(int[] arr) {
		// 先考虑边界条件
		if (arr == null || arr.length < 2) {
			return;
		}
		int N = arr.length;
		for (int i = 1; i < N; i++) {
			int newNumIndex = i;
			while (newNumIndex - 1 >= 0 && arr[newNumIndex-1] > arr[newNumIndex]) {
				swap(arr, newNumIndex-1, newNumIndex);
				newNumIndex--;
			}
		}
	}
	
	/**
	 * 优化排序，减少代码
	 * @param arr
	 */
	public static void insertionSort2(int[] arr) {
		// 先考虑边界条件
		if (arr == null || arr.length < 2) {
			return;
		}
		int N = arr.length;
		for (int i = 1; i < N; i++) {
			for (int j = i - 1; j >= 0 && arr[j] > arr[j+1]; j--) {
				swap(arr, j, j + 1);
			}
		}
	}
	
	public static void swap(int[] arr, int i, int j) {
		int temp = arr[j];
		arr[j] = arr[i];
		arr[i] = temp;
	}
	
	public static void printArray(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int[] arr = {7,1,3,5,8,9,4,6,2};
		printArray(arr);
		insertionSort2(arr);
		printArray(arr);
	}
	
}
